import java.awt.*; import java.applet.*; import java.awt.event.*; import javax.imageio.ImageIO; import java.io.File; import java.awt.image.BufferedImage; import java.io.IOException; public class ImageApplet extends Applet { //===================================================================================================== // The two data fields are needed to share information between methods. //===================================================================================================== public File f; public BufferedImage bi; //===================================================================================================== // We will create the objects for the data fields. This has to be done inside a try/catch statement. // The catch section would only be executed if an IO error occured. We'll leave it blank. //===================================================================================================== public void init() { setBackground(Color.red); try { //--------------------------------------------------------------------------------- //The getCodeBase() method returns an url object that starts with "file:/C:/...". //We need to get the string version of it, remove the "file:/" part of it. //We then need to replace all "%20" with spaces for some reason. // //Note: I am confident this will work on Windows machines. However, you might //not want to replace the %20 on unix machines. //--------------------------------------------------------------------------------- String path = getCodeBase().toString().substring(6).replace("%20"," "); //WILL THIS WORK ON UNIX SERVERS? f = new File(path + "senators.jpg"); bi = ImageIO.read(f); } catch (IOException e) { //Could handle File Not Found error here. We'll just leave it blank. } } //===================================================================================================== // In the paint method, we will simply draw the image. Notice that the image is very easy to work with // after you have brought it into java (inside the init method). //===================================================================================================== public void paint(Graphics g) { Graphics2D g2D = (Graphics2D)g; g2D.drawImage(bi, 50, 50, this); } }